package com.darren.euc.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.darren.euc.dao.UserDao;
import com.darren.euc.entity.PageBean;
import com.darren.euc.entity.User;
import com.darren.euc.service.UserService;
import com.darren.euc.util.StringUtil;

import net.sf.json.JSONObject;


@Service
public class UserServiceImpl  implements UserService {
	
	@Autowired
    private UserDao userDao;
	
    @Override
    public User save(User user) {
        return userDao.save(user);
    }
    
    @Override
    public User update(User user) {
        return userDao.update(user);
    }
    
    
    
	@Override
	public List<User> getAll() {
		return userDao.getAll();
	}
	
	
	@Override
	public User getUserByUserName(String userName) {
		return userDao.getUserByUserName(userName);
	}
	
	@Override
	public User getUserById(Integer id){
		return userDao.findById(id);
	}
	
	@Override
	public List<User> getUserByMobile(String mobile) {
		return userDao.getUserByMobile(mobile);
	}
	
	@Override
	public PageBean queryForPageBySQL(String sql, Integer pageSize, Integer currentPage, Object... objs) {
		return userDao.queryForPageBySQL(sql, pageSize, currentPage, objs);
	}
	
	@Override
	public PageBean queryForPageUseHQLByUserName(String userName,Integer pageSize, Integer currentPage) {
		String HQL = " from User where name like ? or mobile like ? or userName like ? ";
		return userDao.queryForPageByHQL(HQL, pageSize, currentPage,"%"+userName+"%","%"+userName+"%","%"+userName+"%");
	}
	
	@SuppressWarnings("rawtypes")
	public PageBean queryForPageUseHQL(JSONObject requestJson,Integer pageSize, Integer currentPage){		
		String HQL = null;
        Iterator iterator = requestJson.keys();
        List<String> parameters = new ArrayList<String>();
		while(iterator.hasNext()){
			String key = (String) iterator.next();
			key = StringUtil.convertNullToEmptyString(key);
			String value = requestJson.getString(key);
			value = StringUtil.convertNullToEmptyString(value);
			if(!"".equals(value)){
				HQL = (HQL == null?"": HQL + " OR ") +  key + " like ? ";
				parameters.add("%"+value+"%");
			}
		}
		HQL = " from User where enable = true  " + (HQL == null?"":" and " + HQL);
		return userDao.queryForPageByHQL(HQL, pageSize, currentPage,parameters.toArray());
	}
	
	@Override
	public void deleteById(Integer id) {
		User user = userDao.findById(id);
		user.setEnable(false);
		userDao.update(user);
	}
	
	public boolean IsAdmin(Integer userId, Integer functionId) {
		return userDao.IsAdmin(userId, functionId);
	}

	public List<User> getAdminListByFunctionId(String functionId) {
		return userDao.getAdminListByFunctionId(functionId);
	}
	
	public List<User> getUserListByFunctionId(String functionId,Integer userId) {
		return userDao.getUserListByFunctionId(functionId,userId);
	}
	
}